package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public void start() {
        //TODO：【222024321072046/马云山]   实现 ServerSocket 的创建和监听
        try (ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到新的连接：" + clientSocket.getInetAddress());
                threadPool.execute(new RequestProcessor(clientSocket));
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败或运行异常: " + e.getMessage());
            threadPool.shutdown();
        }
    }

    private static class RequestProcessor implements Runnable {
        private final Socket socket;

        public RequestProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            //TODO：【222024321072046/马云山]    完善请求处理流程，确保异常安全和资源关闭
            try {
                Parameter request = HttpParser.parse(socket.getInputStream());
                Router router = new Router();
                router.route(request, socket.getOutputStream());
            } catch (Exception e) {
                System.err.println("请求处理异常: " + e.getMessage());
                try {
                    send500Error(socket.getOutputStream());
                } catch (IOException ex) {
                    System.err.println("发送错误响应失败: " + ex.getMessage());
                    //TODO：【222024321072046/马云山]
                }
            } finally {
                try {
                    if (socket != null) socket.close();
                } catch (IOException e) {
                    System.err.println("关闭socket失败: " + e.getMessage());
                }
            }
        }

        private void send500Error(OutputStream outputStream) {
            PrintWriter writer = new PrintWriter(outputStream);
            String content = "<h1>500 Internal Server Error</h1>";
            writer.println("HTTP/1.1 500 Internal Server Error");
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Content-Length: " + content.getBytes().length);
            writer.println("Connection: close");
            writer.println();
            writer.println(content);
            writer.flush();
        }
    }
}